package com.glw.sso.platform.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 参数校验Validator配置类
 */
@Configuration
public class CacheManageConfig {

    @Autowired
    private CacheNameConfig cacheNameConfig;

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        if (CollectionUtils.isEmpty(cacheNameConfig.getMap())) {
            throw new NullPointerException("需要配置 cache-manager.map");
        }

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        ConcurrentHashMap<String, RedisCacheConfiguration> configMap = new ConcurrentHashMap<>();
        cacheNameConfig.getMap().forEach((k, v) -> configMap.put(k, config.entryTtl(Duration.ofSeconds(v))));

        // 需要先初始化缓存名称，再初始化其它的配置。
        return RedisCacheManager
                .builder(factory)
                .initialCacheNames(cacheNameConfig.getMap().keySet())
                .withInitialCacheConfigurations(configMap)
                .build();
    }

}